#include <iostream>
#include <pthread.h>
#include <functional>
#include <unistd.h>
#include<sys/syscall.h>

using namespace std;

const int NUM = 5;

// using func_t = function<void()>;
typedef function<const char*()> func_t;

class ThreadData
{
public:
    string thread_name;
    uint64_t create_time;
    func_t func;
    ThreadData(string _thread_name,uint64_t _create_time,func_t _func)
    :thread_name(_thread_name),create_time(_create_time),func(_func)
    {}
};

std::string ToHex(pthread_t tid)
{
    char id[64];
    snprintf(id, sizeof(id), "0x%lx", tid);  //转换为16进制
    return id;
}

const char* func_1()
{
    sleep(10);
    cout<<"thread-x exit!"<<endl;
    pthread_exit((void*)"func_1 exit");
    return "func_1 exit!";
}

const char* func_2()
{
    sleep(1);
    return nullptr;
}

void *thread_func(void *arg)
{
    //线程分离
    //pthread_detach(pthread_self()); 

    int a =5;
    ThreadData *td = static_cast<ThreadData*>(arg); //强制类型转换
    while(a--)
    {
        sleep(1);
        cout<<td->thread_name<<" running"<<endl;
        //td->func();
    }
    pthread_exit((void*)"pthread_exit!");  //return (void*)"exit!";
}

pid_t gettid() {
    return syscall(SYS_gettid); //获取线程 tid
}

int main()
{
    // for (int i = 0; i < NUM; i++)
    // {
    //     char threadname[64];
    //     snprintf(threadname, sizeof threadname, "%s-%d", "Thread", i);
       
    //     pthread_t tid;
    //     ThreadData *td = new ThreadData(threadname, (uint64_t)time(nullptr),func_2);
    //     pthread_create(&tid,nullptr,thread_func,td);

    //     sleep(1);
    //     cout<<endl;
    // }

    pthread_t tid;
    ThreadData *td = new ThreadData("Thread-x", (uint64_t)time(nullptr),func_1);  //退出进程
    pthread_create(&tid,nullptr,thread_func,td);
    pthread_detach(tid);

    //sleep(1);

    //cout<<"main tid"<<pthread_self()<<" "<<gettid()<<endl;  //tid LWP

    // int m = pthread_cancel(tid);
    // cout<<"pthread_cancel,m: "<<m<<endl;  //线程取消,join就不会阻塞，等待成功
                                            //线程被分离了也可以取消，但依旧不能等待
    void *exit_message;
    int n = pthread_join(tid,&exit_message);

    cout<<"n: "<<n<<" tid: "<<tid<<"exit_message: "<<(int64_t)exit_message<<endl;
    //cout<<"n: "<<n<<" tid: "<<tid<<"exit_message: "<<(char*)exit_message<<endl;
}


    